// pages/ShoppingCart/index.js
var common = require("../../../public.js");
import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopList: [],
    refreshing: false,
    refresherEnable: false,
    radioChecked: {},
    totalCount: 0,
    totalPrice: 0,
    itemCheckedMap: {}, // 记录选中的商品,key为当前商品的id，value为true
    goodsCheckedList: [] // 记录选中商品的信息
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    wx.getStorage({
      key: 'user',
      success: function (res) {
        console.log(res)
        that.setData({
          userInfo: res.data.user,
          token: res.data.token,
          openid: res.data.openid
        }, () => {
          that.refreshData();
        })
      }
    })
  },
  refreshData(showTopLoading = true) {
    if (this.data.refreshing === true) {
      return
    }
    this.setData({
      refreshing: true,
      refresherEnable: showTopLoading
    })
    const that = this
    let tempJson = {
      userId: that.data.userInfo.id,
      token: that.data.token
    }
    common.wxRequest("/cart/list", "get", tempJson, 'application/json', function (res) {
      if (res.status === 200) {
        let tmpRadioCheckedObject = {}
        const itemCheckedMap = that.data.itemCheckedMap
        const shopArray = res.data.map(function (item, index) {
          const good = item.list[0]

          let childObj = {}
          const list = item.list.map(function (item, index) {
            let obj = item
            const itemId = item.itemId
            const checked = itemCheckedMap[itemId] === true ? true : false
            childObj[item.itemId] = {
              checked: checked,
              item: item
            }
            return obj
          })

          tmpRadioCheckedObject[good.storeId] = {
            checked: false,
            child: childObj
          }

          return {
            storeName: good.storeName,
            storeId: good.storeId,
            checked: false,
            list: list
          }
        })
        that.setData({
          shopList: shopArray,
          radioChecked: tmpRadioCheckedObject,
          itemCheckedMap: {},
          refresherEnable: true
        }, function() {
          that.computeTotal(tmpRadioCheckedObject)
        })
      } else {

      }

      setTimeout(() => {
        that.setData({
          refreshing: false
        })
      }, 500)
    })
  },
  onNumChange(e) {
    const num = e.detail
    const itemId = e.currentTarget.dataset.id
    const that = this
    let tempJson = {
      userId: that.data.userInfo.id,
      token: that.data.token,
      itemId,
      num
    }
    common.wxRequest('/cart/update', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
      if (res.status === 200) {
        that.refreshData(false)
      } else {
        wx.showToast({
          title: res.msg ? res.msg : '删除失败',
          icon: "none"
        })
      }
    })
  },
  onStoreChange(e) {
    const storeId = e.currentTarget.dataset.store
    const radioChecked = this.data.radioChecked
    const storeObj = radioChecked[storeId]
    // 更新店铺的checkbox状态
    storeObj.checked = !storeObj.checked
    // 更新所有孩子节点的CheckBox状态
    const child = storeObj.child
    for (let key in child) {
      child[key].checked = storeObj.checked
    }
    this.computeTotal(radioChecked)
  },
  onCommodityChange(e) {
    const storeId = e.currentTarget.dataset.store
    const itemId = e.currentTarget.dataset.item
    const radioChecked = this.data.radioChecked
    const storeObj = radioChecked[storeId]
    const checked = !storeObj.child[itemId].checked
    storeObj.child[itemId].checked = checked
    this.computeTotal(radioChecked)
  },
  computeTotal(radioChecked) {
    let totalCount = 0
    let totalPrice = 0
    const itemCheckedMap = this.data.itemCheckedMap
    let goodsCheckedList = []
    for (const store in radioChecked) {
      const childrenObject = radioChecked[store].child
      let checkedCounter = 0
      let index = 0
      for (const childKey in childrenObject) {
        index ++
        const childObject = childrenObject[childKey]
        if (childObject.checked) {
          const num = childObject.item.num
          const price = childObject.item.price
          totalCount += num
          totalPrice += (num * price)
          checkedCounter ++
          itemCheckedMap[childKey] = true
          goodsCheckedList.push(childObject.item)
        } else {
          itemCheckedMap[childKey] = false
        }
      }
      // 更新店铺的checkbox
      if (checkedCounter === index) {
        radioChecked[store].checked = true
      }
    }
    this.setData({
      radioChecked,
      totalCount,
      totalPrice,
      itemCheckedMap,
      goodsCheckedList
    })
  },
  onDelete(e) {
    const itemId = e.currentTarget.dataset.id
    const that = this
    that.submitDelete(itemId)
    // Dialog.confirm({
    //   title: '操作提示',
    //   message: '是否删除当前商品？',
    // })
    // .then(() => {
    //   // on confirm
    //   that.submitDelete(itemId)
    // })
    // .catch(() => {
    //   // on cancel
    // });
  },
  submitDelete(itemId) {
    const itemIds = [itemId]
    const that = this
    let tempJson = {
      userId: that.data.userInfo.id,
      token: that.data.token,
      itemIds
    }
    wx.showLoading({
      title: null,
      mask: true,
      success: (res) => {},
      fail: (res) => {},
      complete: (res) => {},
    })
    common.wxRequest('/cart/delete', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
      if (res.status === 200) {
        that.refreshData(false)
      } else {
        wx.showToast({
          title: res.msg ? res.msg : '删除失败',
          icon: "none"
        })
      }
    })
  },
  settlement (){
    if (this.data.totalCount === 0) {
      wx.showToast({
        title: '请选择商品',
        icon: "none"
      })
    } else {
      console.log(this.data.goodsCheckedList)
    }
  }
})